import {Component } from 'react'
import { Input,Select,Button,Table,Switch,DatePicker,ConfigProvider,Modal,message } from 'antd';
import { UserOutlined , PhoneOutlined,ClockCircleOutlined} from '@ant-design/icons';
import './UserManagement.css'
import zh_CN from 'antd/lib/locale-provider/zh_CN';
import 'moment/locale/zh-cn';
import axios from 'axios'
import api from '../api'
import moment from 'moment';


const { Option } = Select;
const { RangePicker } = DatePicker;


class UserManagement extends Component{
    state = {
        current:1,//当前页面
        loading: false,
        total: 0,//分页，总共数据条数
        pageNum: 1,
        pageSize: 8,//每页显示条数
        userList:[],//用户列表
        isModalVisible:false,
        setIsModalVisible:false,
        motalTitle:'',//模态框标题
        isdisabled:false,//模态框内的性别下拉框是否禁用
        userName:'',//用户名
        userTel:'',//电话
        userSex:'男',//性别
        register:'',//注册时间
        userId:0,//用户Id
        userState:1,//用户状态
        searchName:'',//搜索用户名
        searchTel:'',//搜索电话
        searchSex:'请选',//搜索性别 男0，女1
        searchState:'请选',//搜索状态，正常1，封号0
        searchStartTime:undefined,//搜索注册开始日期
        searchEndTime:undefined,//搜索注册结束日期
    };
    onSelectChange = selectedRowKeys => {
        this.setState({ selectedRowKeys });
    };
     //获取数据
    getUserList = ()=>{
       return  new Promise((resolve, reject) => {
            axios.get(api.user.user+"page="+this.state.current+"&limit="+this.state.pageSize).then(res=>{
                if(res.data.code==0){
                    resolve(res.data.data)
                }else {
                    reject()
                }
            })
        })

    }
    async componentDidMount() {
        await this.getUserList().then(res=>{
            let arr = []
            res.list.forEach((item,index)=>{
                arr.push({
                    key:item.userId,
                    name:item.userName,
                    tel:item.userPhone,
                    sex:item.userSex=='0'?'男':'女',
                    time:item.userCreateTime,
                    state:item.userStatus,
                    })
            })
            this.setState({
                userList:arr,
                total:res.total
            })
        })
    }
    //查看
    lookInfo=(data,event)=>{
        this.showModal()
        this.setState({
            motalTitle:'查看',
            isdisabled:true,
            userName:data.name,
            userTel:data.tel,
            userSex:data.sex,
            register:data.time
        })
    }
    //修改
    editInfo=(data)=>{
        this.showModal()
        //显示数据
        this.setState({
            motalTitle:'修改',
            isdisabled:false,
            userName:data.name,
            userTel:data.tel,
            userSex:data.sex,
            register:data.time,
            userId:data.key,//用户Id
            userState:data.state,//用户状态
        })
    }
        //查看模态框
    showModal=()=>{
        this.setState({
            isModalVisible:true
        })
    }
    //状态改变事件
    stateChange(id){
        let currentState=0
        if(id.state==0){
            currentState = 1
        }else {
            currentState=0
        }
       // 修改列表数据数组
        let arr = this.state.userList.map(item=>{
            if(id.key == item.key){
                return {
                    key:item.key,
                    name:id.name,
                    tel:id.tel,
                    sex:id.sex,
                    time:id.time,
                    state:currentState,
                }
            }else {
                return item
            }
        })
        this.setState({
            userState:Number(currentState),
            userList:arr,
            userId:id.key,
            userName:id.name,
            userTel:id.tel,
            userSex:id.sex=='男'?Number(0):Number(1)
        },()=>{this.requestEdit()})

    }
    //模态框输入改变事件
    uerChange(key,event){
        this.setState({
            [key]:event.target.value,
        })
    }
    selectChange=(value)=>{
        this.setState({
            [value.name]:value.value,
        })
}
//时间改变的方法
    onPickerChange=(date, dateString)=>{
        // console.log("data",date,"dateString",dateString);
        // //这两个参数值antd自带的参数
        // console.log("dateString",dateString[0],"dateString",dateString[1]);
        this.setState({
            searchStartTime:dateString[0],
            searchEndTime:dateString[1],
        })
    }
    //模态框确定按钮
    handleOk = (e) => {
        //修改列表数据数组
        let arr = this.state.userList.map((item,index)=>{
            if(this.state.userId == item.key){
                return {
                    key:item.key,
                    name:this.state.userName,
                    tel:this.state.userTel,
                    sex:this.state.userSex,
                    time:this.state.register,
                    state:item.state,
                }
            }else {
                return item
            }
        })
        this.setState({
            isModalVisible:false,
            userList:arr
        })
        this.requestEdit();
    }
    //修改数据接口函数
    requestEdit(){
        //修改数据，返回数据库
        axios.post(api.user.edit, {
            userId:this.state.userId,
            userName:this.state.userName,
            userPhone:this.state.userTel,
            userSex:this.state.userSex=='男'?Number(0):Number(1),
            userStatus:Number(this.state.userState)
        }).then(res=>{
            if(res.data.code==200){
                message.success('修改成功')
            }else {
                message.error('修改失败')
            }
        })
    }
    handleCancel = () => {
        this.setState({
            isModalVisible:false
        })
    };
    //点击搜索事件
    searchInfo=()=>{
        axios.get(api.user.search,{params:{
            userName: this.state.searchName,
            userPhone: this.state.searchTel,
            starTime: this.state.searchStartTime,
            endTime: this.state.searchEndTime,
            userSex: this.state.searchSex=='男'?Number(0):(this.state.searchSex=='女'?Number(1):null),
            userStatus: this.state.searchState=='正常'?Number(1):(this.state.searchState=="封号"?Number(0):null),
        }}).then(res=>{
            console.log(res)
            if(res.data.code==0){
                let arr = []
                res.data.data.list.forEach((item,index)=>{
                    arr.push({
                        key:item.userId,
                        name:item.userName,
                        tel:item.userPhone,
                        sex:item.userSex=='0'?'男':'女',
                        time:item.userCreateTime,
                        state:item.userStatus,
                    })
                })

                this.setState({
                    userList:arr,
                    total:arr.length,
                })
            }
        })
    }
    //页码点击事件
    changePage=(e)=>{
        console.log(e)
        this.setState({
            current:e
        },()=>{
            this.componentDidMount()
        })
    }
    //情况搜索框
    clearForm=()=>{
        this.setState({
            searchName:'',//搜索用户名
            searchTel:'',//搜索电话
            searchSex:'请选',//搜索性别 男0，女1
            searchState:'请选',//搜索状态，正常1，封号0
            searchStartTime:'',//搜索注册开始日期
            searchEndTime:'',//搜索注册结束日期
        })
    }
    render() {
        const dateFormat = 'YYYY-MM-DD';
        const columns = [
            {
                title: '用户昵称',
                dataIndex: 'name',
                align:'center',
            },
            {
                title: '手机号',
                dataIndex: 'tel',
                align:'center',
            },
            {
                title: '性别',
                dataIndex: 'sex',
                align:'center',
            },
            {
                title: '注册时间',
                dataIndex: 'time',
                align:'center',
            },
            {
                title: '状态',
                dataIndex: 'state',
                align:'center',
                render:(text, record, index)=>{
                    return(
                        <Switch checked={record.state==1?true:false} onClick={this.stateChange.bind(this,record)}/>
                    )
                }
            },
            {
                title: '操作',
                dataIndex: 'operate',
                align:'center',
                render:(text, record, index)=>{
                    return(
                        <div>
                            <span onClick={()=>{this.lookInfo(record)}}>查看&nbsp;&nbsp;&nbsp;</span>
                            <span onClick={()=>{this.editInfo(record)}}>修改</span>
                        </div>
                    )
                }
            }
        ];//表格头
         const { selectedRowKeys } = this.state;
         const rowSelection = {
             selectedRowKeys,
             onChange: this.onSelectChange,
             columnWidth:'50px',
             fixed:true
         };
         const paginationProps = {
             showQuickJumper: false,
             showTotal: () => `共${this.state.total}条`,
             pageSize: this.state.pageSize,
             total: this.state.total,  //数据的总的条数
             onChange:(current) => this.changePage(current), //点击当前页码
         }
         return(
             <div className='contanir'>
                 {/*搜索区域*/}
                 <div className='search'>
                     <div className='navSearch' >
                         <Input placeholder="用户昵称" className='navInput'
                                value={this.state.searchName}
                                onInput={this.uerChange.bind(this,'searchName')}
                                prefix={<UserOutlined />}/>
                         <Input.Group compact>
                             状&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;态：
                             <Select value={this.state.searchState}
                                     onChange={(value)=>{this.selectChange({'name':'searchState','value':value})}} >
                                 <Option key='全部'>全部</Option>
                                 <Option key='封号'>封号</Option>
                                 <Option key='正常'>正常</Option>
                             </Select>
                         </Input.Group>
                         <Input.Group compact>
                             性&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;别：
                             <Select value={this.state.searchSex}
                                     onChange={(value)=>{this.selectChange({'name':'searchSex','value':value})}}>
                                 <Option key='全部'>全部</Option>
                                 <Option key="男">男</Option>
                                 <Option key="女">女</Option>
                             </Select>
                         </Input.Group>
                     </div>
                     <div className='navSearch'>
                         <Input placeholder="手机号"
                                className='navInput'
                                value={this.state.searchTel}
                                onInput={this.uerChange.bind(this,'searchTel')}
                                prefix={<PhoneOutlined />} />
                         <div>
                             注册日期：
                             <ConfigProvider  locale={zh_CN}>
                             <RangePicker placeholder={['开始日期','结束日期']}
                                          alue={this.state.searchStartTime===undefined||this.state.searchEndTime===undefined||this.state.searchStartTime===""||this.state.searchEndTime===""?null:[moment(this.state.searchStartTime, dateFormat), moment(this.state.searchEndTime, dateFormat)]}
                                          onChange={this.onPickerChange}
                                          format={dateFormat}/>
                             </ConfigProvider >
                         </div>
                         <div className='butSearch'>
                             <Button onClick={this.searchInfo}>查询</Button>
                             <Button type="text" className='butDetele' onClick={this.clearForm}>清空</Button>
                         </div>
                     </div>
                 </div>
                 {/*显示表单*/}
                 <div className='frmContent'>
                     <Table
                         rowSelection={rowSelection}
                         columns={columns}
                         dataSource={this.state.userList}
                         pagination={paginationProps}/>
                 </div>
                 {/*查看模态框*/}
                 <div>
                     <Modal title={this.state.motalTitle}
                            visible={this.state.isModalVisible}
                            onOk={this.handleOk}
                            onCancel={this.handleCancel}>

                         <div className='motalInput'>
                             <Input size="large"
                                    onInput={this.uerChange.bind(this,'userName')}
                                    value={this.state.userName}
                                    disabled={this.state.isdisabled} prefix={
                                 <div>
                                     用户名&nbsp;&nbsp;
                                     <PhoneOutlined />
                                 </div>} />
                         </div>
                         <div className='motalInput'>
                             <Input size="large"
                                    onInput={this.uerChange.bind(this,'userTel')}
                                    value={this.state.userTel}
                                    disabled={this.state.isdisabled}
                                    prefix={
                                 <div>
                                     手机号&nbsp;&nbsp;
                                     <PhoneOutlined />
                                 </div>} />
                         </div>
                         <div className='motalInput'>
                             <Input size="large"
                                    defaultValue={this.state.register}
                                    disabled prefix={
                                 <div>
                                     注册时间&nbsp;&nbsp;
                                     <ClockCircleOutlined />
                                 </div>} />
                         </div>
                         <div className='motalInput'>
                             <span>性&nbsp;&nbsp;别：&nbsp;</span>
                             <Select size='large'
                                     onInput={this.uerChange.bind(this,'userSex')}
                                     value={this.state.userSex}
                                     disabled={this.state.isdisabled} >
                                 <Select.Option value="0">男</Select.Option>
                                 <Select.Option value="1">女</Select.Option>
                            </Select>
                         </div>

                     </Modal>
                 </div>
             </div>
         )
     }
}
export default UserManagement